const arrayData = [
  {
    id: 1,
    name: 'jack',
    pid: 0
  },
  {
    id: 2,
    name: 'jack',
    pid: 1
  },
  {
    id: 3,
    name: 'jack',
    pid: 1
  },
  {
    id: 4,
    name: 'jack',
    pid: 2
  }
]
/**
 * 一维数组生成树
 * @param {*} source 一维数组
 * @param {*} parentId 父级id 、顶层节点默认无
 * @returns 树结构数据
 */

const buildTreeByArray = (source = [], parentId) => {
  const result = []
  const bit = (root, pid, array) => {
    for (let i = 0; i < root.length; i++) {
      if (root[i].pid == pid) {
        let item = { ...root[i], children: [] }
        array.push(item)
        bit(root, item.id, item.children)
      }
    }
  }
  bit(source, parentId, result)
  return result
}
const tree = buildTreeByArray(arrayData, 0)
console.log(tree)
